<?php
namespace control;
/*
* 合同管理类
*/

class contractClass extends adIndexClass
{
    private const page = 'contract';
    private const table = 'contract';
    private const title = '合同列表';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'contractNo'      => [
                        'name'  => "合同编号",
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'signDate' => [
                        'name'  => "签订日期",
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => "合同名称",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'unitA'         => [
                        'name'  => '甲方单位',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'unitB'          => [
                        'name'  => '乙方单位',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'money'    => [
                        'name'  => '合同金额',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'description'    => [
                        'name'  => '合同描述',
                        'width' => 200,
                    ],
                    'manager'    => [
                        'name'  => '经办人',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'    => [
                        'name'  => '审批状态',
                        'width' => 130,
                        'sort' => 1,
                    ],
                    'isArchive'    => [
                        'name'  => '归档状态',
                        'width' => 130,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "合同编号" => text(array("name" => "contractNo")),
                    "合同名称"     => text(array("name" => "contactName")),
                    "签订日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    "审批状态" => select(["name" => "state", 'option' => $this->stateOption]),
                    "归档状态" => select(["name" => "isArchive", 'option' => ['未归档', '已归档']]),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "archive")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','addArchive',{formName:'listForm'})\" class='spanButton'>加入待归档</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "contractNo" => $this->post('contractNo'),//合同编号
            "name" => $this->post('contactName'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "isArchive" => $this->post('isArchive')
        );
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'signDate');
        }

        //查看自己
        $and .= $this->seeSelf(self::page);

        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;

        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => $array['state']=='草稿'?array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"):[],
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "isArchive":
                        $row[] = $array['isArchive']=='未归档'?"<span style='color: red'>".$array['isArchive']."</span>":$array['isArchive'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'money'      => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width"=>100),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }



    /**
     * 加入待归档
     */
    public function addArchive(): bool|string
    {
        $formName = $this->post('formName');
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否将所选的合同加入待归档？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "加入待归档", "height" => 155, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 加入待归档
     */
    public function addArchiveEdit(): bool|string
    {
        $idArr = $this->post('listId');
        if (!$this->power(self::page, "archive")) {
            $json['warn'] = "你没有" . self::title . "的加入待归档权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        }else {
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $info = query(self::table, "id = '$id'");
                if ($info['isArchive'] != '待归档'){
                    $text .= $this->control['name'] . "归档合同【{$info['name']}】， id：{$id} 失败，不是待归档状态<br>";
                }elseif ($info['state'] != '已通过'){
                    $text .= $this->control['name'] . "归档合同【{$info['name']}】， id：{$id} 失败，还未审核通过<br>";
                }elseif(static::total(array('table'=>'archive',"where"=>"targetId = '$info[id]'")) >0){
                    $text .= $this->control['name'] . "归档合同【{$info['name']}】， id：{$id} 失败，此合同已加入待归档<br>";
                }else{
                        $warn = static::insert(array(
                            'table'=>'archive',
                            'field'=>[
                                'id'=>self::getId(),
                                'type'=>'合同管理',
                                'targetId'=>$id,
                                'orderNo'=>$info['contractNo'],
                                'name'=>$info['name'],
                                'level'=>'内部',
                                'transferStid'=>self::$stid,
                                'transferDate'=>$this->date,
                                'transferDept'=>self::findStaffDepartment(self::$stid,'id'),
                                'workFlow'=>'待归档',
                                'fileDate'=>$info['signDate'],
                            ]
                        ));

                    if ($warn == '新增成功') {
                        $x++;
                        $text .= $this->control['name'] . "归档合同【{$info['name']}】， id：{$id}<br>";
                    } else {
                        $text .= $this->control['name'] . "归档合同【{$info['name']}】， id：{$id} 失败，更新失败<br>";
                    }
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => self::page, "text" => $text]);
            }
            $_SESSION['warn'] = "成功将{$x}个合同加入了待归档，详情请查看系统日志";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }


    /**
     * 编辑页
     *
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "合同类别：" => select(array('name' => 'type', 'title' => '合同类别', 'option' => explode('，', para('contractType')), 'value' => $info['type'])),
                    must . "甲方单位：" => text(["name" => "unitA", 'class' => 'text', "value" => $info['unitA']]),
                ],
                [
                    must . "乙方单位：" => text(["name" => "unitB", 'class' => 'text', "value" => $info['unitB']]),
                    must . "合同编号：" => text(["name" => "contractNo", 'class' => 'text', "value" => $info['contractNo']]),
                ],
                [
                    must . "合同名称：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                    "合同描述：" => text(["name" => "description", 'class' => 'text', "value" => $info['description']]),
                ],
                [
                    must . "合同金额：" => text(["name" => "money", 'unit' =>  static::$unit , "value" => $info['money']]),
                    "经办人：" => text(["name" => "manager", 'class' => 'text', "value" => $info['manager']]),
                ],
                [
                    "签订日期：" => text(["name" => "signDate", 'laydate' => [], "value" => $info['signDate']]),
                ],
                [
                    "支付及结算方式：" => textarea(["name" => "payType", 'class' => 'textarea', "value" => $info['payType']]),
                ],
                [
                    "备注：" => textarea(["name" => "text", 'class' => 'textarea', "value" => $info['text']]),
                ],
                [
                    "附件：" => fileUploadClass::addFileComponent($info['id'], '合同管理', self::page, self::page . 'EditForm'),
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 500, "html" => $html));
    }

    public function editEdit()
    {
        $fileIdArr = $this->post('fileId');
        $id = $this->post('id') ?: self::getId();
        $field = [
            'type' => $this->post('type'),
            'unitA' => $this->post('unitA'),
            'unitB' => $this->post('unitB'),
            'contractNo' => $this->post('contractNo'),
            'name' => $this->post('name'),
            'description' => $this->post('description'),
            'money' => $this->post('money'),
            'manager' => $this->post('manager'),
            'signDate' => $this->post('signDate'),
            'payType' => $this->post('payType'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'type' => '合同类别',
            'unitA' => '甲方单位',
            'unitB' => '乙方单位',
            'contractNo' => '合同编号',
            'name' => '合同名称',
            'money' => '合同金额',
        ];
        $rules = [
            'type' => 'required',
            'unitA' => 'required',
            'unitB' => 'required',
            'contractNo' => 'required',
            'name' => 'required',
            'money' => 'required|numeric',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif(static::total(array('table'=>self::table,"where"=>"contractNo = '$field[contractNo]' and id !='$id'")) >0){
            $json['warn'] = '已存在此合同编号';
        }else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'HT' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'deptName' => $department['name'],
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                    'time' => $this->time,
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     *
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => [
                    "act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'name' => '合同管理',
                        'table' => self::table,
                        'process' => [
                            // 预览函数
                            'detail' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'detail',
                            ],
                            //执行发起时验证函数
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => [
                    "act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿', '已通过'],
                        ],
                        // 审核时回调
                        'process' => [
                            //执行首次审核时验证
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //执行末次审核后处理
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
                'style' => 'li-btn-blue-bg',
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿'],
                        ],
                        'process' => [
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        return $button;
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );

            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "del") && $info['state'] == '草稿'){
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            //审核按钮
            $button = array_merge($this->auditButton($info),$button);
            $audit = query('audit', " targetId = '$info[id]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '详细信息' => array(
                    array(
                        "合同类别" => $info['type'],
                        "甲方单位" => $info['unitA'],
                        "乙方单位" => $info['unitB'],
                        "合同编号" => $info['contractNo'],
                    ),
                    array(
                        "合同名称" => $info['name'],
                        "合同描述" => $info['description'],
                        "合同金额" => $info['money'],
                        "经办人" => $info['manager'],
                    ),
                    array(
                        "签订日期" => $info['signDate'],
                    ),
                    array(
                        "支付及结算方式" => pre($info['payType']),
                    ),
                    array(
                        "备注" => pre($info['text']),
                    ),
                ),
                '附件' => array(
                    array(
                        fileUploadClass::showFile($info['id'], '合同管理')
                    )
                ),
                '系统信息' => array(
                    array(
                        "单据编号" => $info['orderNo'],
                        "申请部门" => $info['deptName'],
                        "申请人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                    ),
                    array(
                        "提交时间" => self::null($audit['commitTime']),
                        '状态' => $info['state'],
                    ),
                ),
                '流程' => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id']),
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = "不是草稿状态，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    $all = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($all['array'] as $val) {
                        fileDelete($val['src']);
                        delete(array("table" => 'file', "where" => " id = '$val[id]' "));
                    }
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
